package cn.kbyue.oauth2jwt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * @author XL
 * @version 0.1
 * @date 2021/7/27 22:28
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Bean
    JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // converter.setSigningKey("123456"); -> converter.setVerifierKey("123456");
        converter.setKeyPair(keyPair());
        return converter;
    }

    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return factory.getKeyPair("jwt", "123456".toCharArray());
    }

    /**
     * JWT内容增强
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            Map<String, Object> map = new HashMap<>(2);
            User user = (User) authentication.getUserAuthentication().getPrincipal();
            map.put("JWT_USER_NAME", user.getUsername());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
            return accessToken;
        };
    }

    /**
     * 授权码模式专用对象
     * 可选模式：
     *   - JdbcAuthorizationCodeServices    - table: oauth_code
     *   - InMemoryAuthorizationCodeServices
     *   - RandomValueAuthorizationCodeServices
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * token保存策略
     * 可选策略：
     *   - InMemoryTokenStore
     *   - JdbcTokenStore    - table: oauth_access_token, oauth_refresh_token
     *   - JwkTokenStore
     *   - JwtTokenStore
     *   - RedisTokenStore
     */
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    /**
     * 授权信息保存策略
     * 可选策略:
     *   - InMemoryApprovalStore
     *   - JdbcApprovalStore    - table: oauth_approvals
     *   - TokenApprovalStore
     */
    @Bean
    public ApprovalStore approvalStore() {
        return new JdbcApprovalStore(dataSource);
    }

    /**
     * OAuth2 端点配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        // List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        // tokenEnhancers.add(tokenEnhancer());
        // tokenEnhancers.add(jwtAccessTokenConverter());
        // tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);

        endpoints
                .tokenStore(tokenStore())
                // token 附加信息
                // .tokenEnhancer(tokenEnhancerChain())
                .approvalStore(approvalStore())
                .authorizationCodeServices(authorizationCodeServices())
                // 支持 password 模式
                .authenticationManager(authenticationManager)
                // JWT 模式一. 使用 自定义的 jwtConverter
                .accessTokenConverter(jwtAccessTokenConverter())
                // JWT 模式二. 使用默认的 jwtConverter
                // .accessTokenConverter(jwtAccessTokenConverter)
                .userDetailsService(userDetailsService);
    }

    /**
     * 配置可访问 客户端信息 oauth-client-details
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .jdbc(dataSource)
                .passwordEncoder(passwordEncoder);
    }

    /**
     * 检测 token 的安全策略
     * 其中的 配置项也可通过配置文件设置
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 允许form表单客户端认证,允许客户端使用client_id和client_secret获取token
                .allowFormAuthenticationForClients()
                // 通过验证返回token信息
                .checkTokenAccess("permitAll()")
                // 获取token请求不进行拦截
                .tokenKeyAccess("permitAll()")
                .passwordEncoder(passwordEncoder);
    }
}
